package fr.dsax.nounet.belote.dao;

import java.util.HashMap;
import java.util.Map;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import fr.dsax.nounet.belote.jpa.GenericEntity;

@Component
public class DaoFactory implements IDaoFactory,
		ApplicationListener<ContextRefreshedEvent> {
	
	private Map<Class<? extends GenericEntity>, IGenericDao<?>> daos  = new HashMap<Class<? extends GenericEntity>, IGenericDao<?>>();
	
	@SuppressWarnings("unchecked")
	@Override
	public <T extends GenericEntity> IGenericDao<T> getDaoFor(Class<T> entityClass) {
		return (IGenericDao<T>) daos.get(entityClass);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		ApplicationContext ctx = event.getApplicationContext();
		daos.clear();
		Map<String, IGenericDao> detectedDaos = ctx
				.getBeansOfType(IGenericDao.class);
		for (IGenericDao<GenericEntity> dao : detectedDaos.values()) {
			daos.put(dao.getEntityClass(), dao);
		}
	}

}
